<?php
// 读取JSON数据
$jsonFilePath = __DIR__ . '/../../template/datas/index.json';
if (!file_exists($jsonFilePath)) {
    die('JSON文件不存在: ' . $jsonFilePath);
}

$jsonData = file_get_contents($jsonFilePath);
$data = json_decode($jsonData, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    die('JSON解析错误: ' . json_last_error_msg());
}

// 获取主题设置
$theme = $data['settings']['theme'];
$layout = $data['settings']['layout'];
$components = $data['components'];
$pageName = $data['name'];

// 替换模板文件
$templateFilePath = __DIR__ . '/../../template/views/index.html';
if (!file_exists($templateFilePath)) {
    die('模板文件不存在: ' . $templateFilePath);
}

$templateContent = file_get_contents($templateFilePath);

// 替换页面标题
$templateContent = str_replace('<title>智联科技 - 企业数字化解决方案提供商</title>', '<title>' . $pageName . '</title>', $templateContent);

// 替换Tailwind配置中的颜色值
$colorsReplace = "      theme: {
        extend: {
          colors: {
            primary: '{$theme['primaryColor']}',
            secondary: '{$theme['secondaryColor']}',
            accent: '{$theme['accentColor']}',
            dark: '{$theme['textColor']}',
            light: '{$theme['lightColor']}'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }";

$templateContent = preg_replace('/      theme: \{\s*extend: \{\s*colors: \{[^}]*\},\s*fontFamily: \{[^}]*\},\s*\},\s*\}/', $colorsReplace, $templateContent);

// 替换section-padding工具类值
$paddingValue = str_replace('px 0', '', $layout['sectionPadding']);
$sectionPaddingReplace = "      .section-padding {\n        @apply py-{$paddingValue};\n      }";
$templateContent = preg_replace('/      \.section-padding \{\s*@apply py-[^;]+;\s*\}/', $sectionPaddingReplace, $templateContent);

// 在body标签后插入组件渲染代码
$bodyTagPosition = strpos($templateContent, '<body');
if ($bodyTagPosition !== false) {
    $bodyEndPosition = strpos($templateContent, '>', $bodyTagPosition) + 1;
    $componentsRenderCode = "\n\n  <!-- 组件加载容器 -->\n  <div id=\"components-container\">\n    <?php\n    // 动态加载所有组件\n    foreach (\$components as \$component) {\n        \$componentType = \$component['type'];\n        \$componentFile = __DIR__ . '/components/' . \$componentType . '.html';\n        if (file_exists(\$componentFile)) {\n            include \$componentFile;\n        }\n    }\n    ?>\n  </div>\n\n";
    $templateContent = substr_replace($templateContent, $componentsRenderCode, $bodyEndPosition, 0);
}

// 保存修改后的模板
$outputFilePath = __DIR__ . '/../../template/views/index_processed.php';
file_put_contents($outputFilePath, '<?php\n$components = ' . var_export($components, true) . ';\n?>' . $templateContent);

// 同时更新原始index.html文件（如果需要直接预览）
$htmlOutputPath = __DIR__ . '/../../template/views/index.html';
file_put_contents($htmlOutputPath, $templateContent);

echo "模板替换完成！\n";
echo "已生成可直接使用的PHP模板文件: $outputFilePath\n";
echo "已更新原始HTML文件: $htmlOutputPath\n";